//
//  MTStoreDetailViewController.m
//  ebook
//
//  Created by mt on 17/1/9.
//  Copyright © 2017年 Moton. All rights reserved.
//

#import "MTStoreDetailViewController.h"
#import "NativeStoreHeadCell.h"
#import "NativeStoreContentCell.h"
#import "NativeStoreRecommendCell.h"
#import "EbookNetRequest.h"
#import "Book.h"
#import "UIImageView+WebCache.h"
#import "BookcaseOprationController.h"
#import "DownloadModel.h"
#import "DownloadManager.h"
#import "ReaderBookModel.h"
#import "ReaderViewController.h"
#import "MBProgressHUD.h"
#import "NSString+Time.h"
#import "MISAlertController.h"

@interface MTStoreDetailViewController ()<UITableViewDelegate, UITableViewDataSource, NativeStoreHeadCellDelegate,NativeStoreContentCellDelegate, NativeStoreRecommendCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, assign) BOOL isCellExpanded;//cell状态 YES:打开 NO:折叠
@property (nonatomic, strong) MBProgressHUD *HUD;

@end

@implementation MTStoreDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    [self createBackBtn];
    
    [self.view addSubview:self.tableView];
    [self showHud];
    [self getResultrecommendlist];
}

- (void)getResultrecommendlist {
    
    
    NSInteger page = 1;
    NSInteger sort = [_model.sortid integerValue];
    NSInteger fullflag = [_model.fullflag integerValue];
    /*
    [EbookNetRequest getNativeStoreWithPage:page sort:sort fullflag:fullflag order:_order success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        
        NSDictionary *resp = dict[@"resp"];
        
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *dic in resp[@"Items"]) {
            NativeOrderlistModel *model = [[NativeOrderlistModel alloc] initWithDictionary:dic];
            model.lastupdate = [@"" interceptTimeStampFromStr:model.lastupdate];
            model.sortname = _model.sortname;
            [tempArray addObject:model];
        }
        
        _dataArray = [NSArray arrayWithArray:tempArray];
        [_tableView reloadData];
        [self hideHud];
        
    } failed:^(int stateCode, NSString *failMsg) {
        [self showFailedView];
    }];  */
}
- (void)reloadView {
    [self hideHud];
    [self hideFailedView];
    [self getResultrecommendlist];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - backBtn
- (void)createBackBtn
{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    backItem.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH-SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.separatorColor = MTColor(243, 243, 243, 1.0);
    }
    return _tableView;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section==0?2:1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            return 290.0;
        } else {
            return _isCellExpanded?[self getHeightWithText:_model.introduction]:kNativeStoreContentCellHeight;
        }
    } else {
        return kNativeStoreRecommendCellHeight;//315.0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            
            static NSString *identifier = @"identifier0";
            NativeStoreHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[NativeStoreHeadCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.delegate = self;
            cell.model = _model;
            return cell;
        } else {
            static NSString *identifier = @"identifier1";
            NativeStoreContentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[NativeStoreContentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.delegate = self;
            cell.model = _model;
            
            CGFloat height = [self getHeightWithText:_model.introduction];
            cell.rowHeight = _isCellExpanded?height:kNativeStoreContentCellHeight;
            height<kNativeStoreContentCellHeight?(cell.isHiddenPackBtn = YES):(cell.isHiddenPackBtn = NO);
            
            return cell;
        }

    } else {
        static NSString *identifier = @"identifier2";
        NativeStoreRecommendCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (!cell) {
            cell = [[NativeStoreRecommendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.hotSearchTitle = [NSString stringWithFormat:@"热门%@小说", _model.sortname];
        cell.resultCell2Array = _dataArray.count>8?[_dataArray subarrayWithRange:NSMakeRange(0, 8)]:_dataArray;
        cell.delegate = self;
        return cell;
    }
}

- (CGFloat)getHeightWithText:(NSString *)text {
    return [text boundingRectWithSize:CGSizeMake(MTScreenW-30, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0]} context:nil].size.height+140;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.y<=0) {
        [scrollView setContentOffset:CGPointZero];
    }
}

#pragma mark - NativeStoreHeadCell
- (void)nativeStoreHeadCell:(NativeStoreHeadCell *)cell btnClickedWithTag:(NSInteger)tag {
    MTLog(@"%ld", tag);
    
    switch (tag) {
        case 100://立即阅读
            [self pushToReader];
            break;
        case 101://加入书架
            [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateBookshelfNotification object:_model.bookid];
            
            break;
        case 102://全本缓存
            [self wholeDownload];
            break;
        case 200://收藏
            
            break;
        case 201://目录
            
            break;
        case 202://推荐
            
            break;
        case 203://分享
            [self shareBook];
            
            break;
            
        default:
            break;
    }
}


#pragma mark - NativeStoreContentCell
- (void)nativeStoreContentCell:(NativeStoreContentCell *)cell isCellFold:(BOOL)isFold {
    
    _isCellExpanded = isFold;
    [_tableView reloadData];
}

#pragma mark - NativeStoreRecommendCellDelegate
- (void)nativeStoreRecommendCell:(NativeStoreRecommendCell *)cell selectedWithBook:(NativeOrderlistModel *)book {
    
    MTStoreDetailViewController *resultVc = [[MTStoreDetailViewController alloc] init];
    resultVc.title = book.bookname;
    resultVc.model = book;
    resultVc.order = _order;
    [self.navigationController pushViewController:resultVc animated:YES];
}

-(MBProgressHUD *)HUD{
    if (!_HUD) {
        _HUD = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
        _HUD.center = self.view.center;
    }
    return _HUD;
}

- (void)showHUD{
    [self.view addSubview:self.HUD];
    [self.view bringSubviewToFront:self.HUD];
    [self.HUD show:YES];
}

-(void)hideHUD{
    [self.HUD removeFromSuperview];
}

//立即阅读
- (void)pushToReader{
    
    if(!_model)return;
    
    Book *book = [self setBookWithNativeModel];
    ReaderBookModel *readerbookModel = [[ReaderBookModel alloc] initWithBook:book isMiddleIn:NO];
    [self showHUD];
    double time = 0;
    if(![readerbookModel isExistCurrentChapter]){
        self.HUD.labelText = kInfoNetLoad;
        time = [[NSDate date] timeIntervalSince1970];
    }else{
        self.HUD.labelText = kInfoLocalLoad;
    }
    
    [readerbookModel getInitPageDataComplete:^(NSDictionary *dict,TurnResult result) {
        
        NSArray *array = [dict objectForKey:@"data"];
        if(!dict||!array||[array count]==0||result==TurnNoNet){//未获取到内容
            [ToastView showMsg:kContentErrorNoNetInfo inView:self.view isCenter:YES];
            [self.HUD removeFromSuperview];
            return ;
        }
        
        double inteval = 0.0f;
        if(time>0)inteval = 2.0 - ([[NSDate date] timeIntervalSince1970]-time);
        inteval = inteval<0?0:inteval;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, inteval * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [self.HUD removeFromSuperview];
            ReaderViewController *reader = [[ReaderViewController alloc] init];
            reader.readerBookModel = readerbookModel;
            [reader loadPageviewDatasource:dict];
            
            [self.navigationController pushViewController:reader animated:YES];
        });
    }];
}


//分享
-(void)shareBook {
    
    NSString *intro = _model.introduction;
    NSString *text = intro.length>120?[intro substringToIndex:120]:intro;
    UIImageView *imageV = [[UIImageView alloc] init];
    UIView *shareView = nil;
    if (isIpad) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(MTScreenW/8*7-50, MTScreenH/4+30, 10, 10);
        [self.view addSubview:btn];
        
        shareView = btn;
    }
    NSDictionary *dict = @{@"imgurl":_model.coverpicurl,@"title":_model.bookname};

    if (!_model.coverpicurl) {
        imageV.image = [UIImage imageNamed:@"share"];
        [super sharewithview:shareView text:text dic:dict imagesArray:@[imageV.image]];
    } else {
        [imageV sd_setImageWithURL:[NSURL URLWithString:_model.coverpicurl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [super sharewithview:shareView text:text dic:dict imagesArray:@[image?image:[UIImage imageNamed:@"share"]]];
        }];
    }
}

//全本缓存
-(void)wholeDownload{
    
    //对于需要全本缓存的书，先将书添加到书架
    Book *book = [self setBookWithNativeModel];
    [BookcaseOprationController addBookcase:book.bookid success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateBookshelfNotification object:book.bookid];
        MTLog(@"点击全本缓存，添加书架成功");
        
        //全本下载时不需要获取章节列表，章节列表直接存在压缩包里
        DownloadModel *download = [[DownloadModel alloc] init];
        download.book = book;
        download.chapter = nil;
        download.chapterList = nil;
        download.downloadType = Download_all;
        [[DownloadManager shareInstance] addDownload:download];//开始下载
    } failed:^(int stateCode, NSString *failMsg) {
        
        MTLog(@"点击全本缓存，添加书架失败");
        MISAlertController *alertController = [MISAlertController alertControllerWithTitle:@"缓存失败" message:failMsg preferredStyle:UIAlertControllerStyleAlert];
        MISAlertAction *okAction = [MISAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [alertController showInViewController:self animated:YES];
    }];
}

- (Book *)setBookWithNativeModel {
    
    Book *book = [[Book alloc] init];
    book.bookid = _model.bookid;
    book.bookname = _model.bookname;
    book.author = _model.author;
    book.coverpicurl = _model.coverpicurl;
    book.fullflag = _model.fullflag;
    book.updatetime = _model.lastupdate;
    book.firstchapterid = _model.firstchapterid;
    book.firstchaptername = _model.firstchapter;
    return book;
}

@end
